/*
 * @Descripttion: 
 * @Author: cuidm
 * @Date: 2022-07-13 09:26:36
 * @LastEditors: cuidm
 * @LastEditTime: 2022-08-24 17:57:06
 */

import React, { useEffect, useState } from "react";
import { Affix, Button, Alert, Radio, Select, Input, Space, Row, Col, Tree, message, Spin } from "antd";
import request, { exportFile } from "@/utils/request";
import cmdbres from "@/data/cmdbres";
import CreateNode from './createNode';
import CreateSetInstance from './createSetInstance';
import CreateServiceInstance from './createServiceInstance';
import "../index.less";

const BusinessTree = ({ history, match, location, biz, setSelectTreeNode ,setSelectModuleId}) => {
    const [loading, setLoading] = useState(false);
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [allTreeData, setAllTreeData] = useState([]);
    const [treeData, setTreeData] = useState([]);
    const iconName = (code, instanceName) => {
        let name = { biz: "业", set: "集", service: "模" }[code];
        let f = instanceName?.substring(0,1)??'层';
        return  name ? name : f
    }
    
    const [showModule, setShowModule] = useState(false);
    const [info, setInfo] = useState({});
    const [bizChain, setBizChain] = useState([]);
    const [searchValue, setSearchValue] = useState('');

    const renderTitle = (item) => {
        const {instanceName} = item;
        return (
            <>
                <span>{instanceName}</span>
                {item.moduleCode != 'service' &&
                <Button className="btn" type="primary" onClick={async(e)=>{
                    e.stopPropagation();
                    let chains = [...bizChain];
                    if(!chains.length) {
                        chains = await queryMainLine();
                    } 
                    const chain = chains.find(c=> item.moduleCode == c.moduleCode);
                    if(!chain) {
                        message.error("未查询到下一级业务拓扑模型！");
                        return;
                    }
                    Object.assign(item, {
                        bizId: biz.cm_unid,
                        nextModuleId: chain.nextModuleId,
                        nextModuleName: chain.nextModuleName,
                        nextModuleCode: chain.nextModuleCode,
                    })
                    setShowModule(true);
                    setInfo(item);
                }}>新建</Button>
                }
            </>
        )
    }

    const dealTopoData = (data) => {//拓扑列表
        data.map(item=> {
            const {instanceId, instanceName, moduleCode, children } = item;
            const obj = {
                key: instanceId,
                title: renderTitle(item),
                icon: <span className="icon">{iconName(moduleCode, instanceName)}</span>
            }
            Object.assign(item, obj);
            if(children) {
                // item.children = child;
                // delete item.child;
                dealTopoData(item.children)
            };
        })

        return data;
    }

    //空闲机池
    const dealPools = (pools) => {
        let obj = Object({
            key: pools.setId,
            title: pools.setName,
            icon: <span className="icon">{iconName('', pools.setName)}</span>,
            children: [],
            moduleCode:pools.moduleCode
        },pools);

        if(pools.serviceInstances) {
            pools.serviceInstances.map(item=> {
                obj.children.push({
                    key: item.serviceId,
                    title: item.serviceName,
                    icon: <span className="icon">{iconName('', item.serviceName)}</span>,
                    ...item
                })
            })
            delete obj.serviceInstances;
        }
        return obj;
    }

    const queryBizPool = async () => {
        try {
            const res = await request({
                ...cmdbres.queryBizPool(biz.cm_unid),
                params: {},
            });
            return res && res.data ? dealPools(res.data) : {};
        } catch (error) {
            console.log(error);
        } 
    };

    const queryBizTopologyList = async () => {
        try {
            const res = await request({
                ...cmdbres.queryBizTopologyList(biz.cm_unid),
                data: {},
            });
            if(res && res.data) {
                let arr = [];
                const node = {
                    ...res.data,
                    children: []
                };
                // delete node.child;
                arr.push({
                    ...node,
                    key: node.instanceId,
                    title: renderTitle(node),
                    icon: <span className="icon">{iconName(node.moduleCode, node.instanceName)}</span>
                })
                if(res.data.children && res.data.children.length) {
                    arr[0].children = dealTopoData(res.data.children);
                }
                console.log('arr123',arr)

                return arr;
            }
            return [];
        } catch (error) {
            console.log(error);
        } 
    };

    const fetchData = async(init) => {
        setLoading(true);
        const [treeArr, poolData] = await Promise.all([queryBizTopologyList(), queryBizPool()]);
        if(treeArr && poolData) {
            if(treeArr.length) {
                if(JSON.stringify(poolData) != "{}") {
                    treeArr[0].children.unshift(poolData);
                }

                if(init) {
                    onExpand([treeArr[0].key])
                    setSelectTreeNode(treeArr[0]);
                }
            }
            setTreeData(treeArr);
            setAllTreeData(treeArr);
        }
        setLoading(false);
      };
  
    useEffect(() => {
        if(biz)
            fetchData(true);  
    }, [biz])
 
    const queryMainLine = async () => {
        try {
            const res = await request({
                ...cmdbres.queryMainLine,
                params: {},
            });
            if(res && res.data) {
                setBizChain(res.data);
                let selectModuleData = (res.data || []).find(v => v.moduleName ==  '云主机');
                setSelectModuleId(selectModuleData.moduleId ||'')
                console.log('selectModuleId',selectModuleData.moduleId);
                return res.data;
            } else {
                setBizChain([]);
                return [];
            }
        } catch (error) {
            console.log(error);
        } 
    };

    useEffect(() => {
        queryMainLine();
    }, [])

    const onExpand = (keys) => {
        setExpandedKeys(keys);
    };

    const searchTree = (value)=> {
        if(!value) {
            setTreeData(allTreeData);
            return;
        } 
        let newData = [];
        onFuzzyTreeList('instanceName', value, allTreeData, newData);
        console.log(newData);
        setTreeData(newData);
    }

    const onFuzzyTreeList = (key, value, treeList, saveList = []) => {
        return new Promise((resolve, reject) => {
          treeList.forEach(item => {
            if (item[key].indexOf(value) > -1) {
              saveList.push(item);
            } else {
              if (item.children && item.children.length > 0) {
                const _reData = onFuzzyTreeList(key, value, item.children, saveList);
                if (_reData && _reData.length > 0) {
                  saveList.push({
                    ...item,
                    children: _reData
                  })
                }
              }
            }
          })
       
          resolve(saveList)
        })
    }


    return (
        <>
        <Input.Search
            enterButton
            placeholder="按名称模糊搜索"
            value={searchValue}
            onChange={(e) => {
                setSearchValue(e.target.value);
            }}
            onSearch={(value) => {searchTree(value)}}
            style={{ margin: 10, width: `calc(100% - 20px)` }}
        />
        {loading ? <Spin className="topo-tree-spin"/>:
            <Tree
                className="topo-tree"
                showIcon
                expandedKeys={expandedKeys}
                defaultSelectedKeys={expandedKeys}
                treeData={treeData}
                onSelect={(selectedKeys, e) => {
                    if(setSelectTreeNode) setSelectTreeNode(e.node);
                }}
                onExpand={onExpand}
                defaultExpandAll
            />
        }
        {//业务创建拓扑层实例，拓扑层创建集群，集群创建服务
        info && (info.nextModuleCode !="service" && info.nextModuleCode !="set") && 
            <CreateNode 
                info={info}
                visible={showModule}
                setVisible={setShowModule}
                onCreateFinish={()=>{fetchData(false)}}
            />
        }
        {info && info.nextModuleCode =="set" && 
            <CreateSetInstance 
                info={info}
                visible={showModule}
                setVisible={setShowModule}
                onCreateFinish={()=>{fetchData(false)}}
            />
        }
        {info && info.nextModuleCode=="service" && 
            <CreateServiceInstance 
                info={info}
                visible={showModule}
                setVisible={setShowModule}
                onCreateFinish={()=>{fetchData(false)}}
            />
        }
        
        </>
    )
}

export default BusinessTree;
